package com.foreveross.crawl.adapter.sub.impl20140402.v3;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.http.client.methods.HttpGet;

import com.foreveross.crawl.adapter.AbstractAdapter;
import com.foreveross.crawl.adapter.PlaneInfoEntityBuilder;
import com.foreveross.crawl.common.util.RandomBrowserVersion;
import com.foreveross.crawl.common.util.RegHtmlUtil;
import com.foreveross.crawl.domain.airfreight.CabinEntity;
import com.foreveross.crawl.domain.airfreight.single.SinglePlaneInfoEntity;
import com.foreveross.crawl.exception.FlightInfoNotFoundException;
import com.foreveross.taskservice.common.bean.TaskModel;

/**
 * 厦门航空适配器 新模型 优先解决国际数据
 * 
 * @author guokenye
 * 
 */
public class XiaMenAirAdapter extends AbstractAdapter {
	public static final long XiaMen_ChannelId = 11L;
	

	private String random = null;

	public XiaMenAirAdapter(TaskModel taskQueue) {
		super(taskQueue);
	}

	@Override
	public Object fetch(String url) throws Exception {
		return fetchDomeOneWay();
	}
	
	/**
	 * 进入国内数据 国内数据是同一个client
	 * 
	 * @return
	 * @throws Exception
	 */
	private Object fetchDomeOneWay() throws Exception {
		HttpGet get = null;
		String html = null;
		try{
			 //进入第一层，取回，random
			this.fetchFirstRandom();
			
			get = new HttpGet(this.getUrl());
			get.setHeader("Host", "et.xiamenair.com.cn");
			get.setHeader("User-Agent",RandomBrowserVersion.getBV().getUserAgent());
			get.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			get.setHeader("Accept-Encoding", "gzip, deflate");
			get.setHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
			get.setHeader("Referer", "http://www.xiamenair.com/cn/cn/");
			html = excuteRequest(get);
			super.appendPageContents(html);
			return html;
		}finally{
			get = null;
			html = null;
		}
	}
	/**
	 * 第一层url
	 * @throws Exception 
	*/
	public void fetchFirstRandom() throws Exception{
		StringBuffer url = null;
		String html  = null;
		HttpGet get = null;
		try{
			url=new StringBuffer("http://et.xiamenair.com/xiamenair/book/findFlights.action?");
			url.append("tripType=0");
			url.append("&queryFlightInfo=");
			url.append(super.taskQueue.getFromCity()+",");
			url.append(super.taskQueue.getToCity()+",");
			url.append(super.taskQueue.getFlightDate());
			get = super.getBaseGet(url.toString(), null);
			get.setHeader("Host", "et.xiamenair.com.cn");
			get.setHeader("User-Agent", RandomBrowserVersion.getBV().getUserAgent());
			get.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			get.setHeader("Accept-Encoding", "gzip, deflate");
			get.setHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
			get.setHeader("Referer", "http://www.xiamenair.com/cn/cn/"); 
			html = super.excuteRequest(super.getBaseGet(url.toString(), null));
			 super.appendPageContents(html);
			random = RegHtmlUtil.regStr(html,"<input id=\"random\" type=\"hidden\" value=\"([0-9A-Za-z]{4,8})\"></input>");
		}finally{
			url = null;
			html = null;
		}
	}
	

	@Override
	public List<Object> paraseToVo(Object obj) throws Exception {
		return paraseDomeOneWay(obj);
	}

	/**
	 * 解析国内单程
	 * 
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	private List<Object> paraseDomeOneWay(Object obj) throws Exception {
		List<Object> result = new ArrayList<Object>();
		List<JSONObject> cabinData = new ArrayList<JSONObject>();
		JSONObject flighObje=null;
		JSONArray jsonArr = null;
		SinglePlaneInfoEntity singleEntity=null;
		try{
			flighObje = JSONObject.fromObject(obj);//把整个对象转为JSON
			jsonArr = flighObje.getJSONArray("flightInfos1");//只有单程一段
			for(int i=0;i < jsonArr.size();i++){
				flighObje =jsonArr.getJSONObject(i);
				String carry=flighObje.getString("airline");//航空公司简称：airline : "MF"
				String flightNo=flighObje.getString("fltNo");//航班号
				String startTime=flighObje.getString("takeoffTime");//出发时间：takeoffTime : "2014-08-02 07:00"
				String endTime=flighObje.getString("arrivalTime");//到达时间：arrivalTime : "2014-08-02 08:05"
				String type=flighObje.getString("equipment");//貌似是机型equipment : "738"
				singleEntity=(SinglePlaneInfoEntity)PlaneInfoEntityBuilder.
						buildPlaneInfo(taskQueue, "MF", "厦航", "厦门航空公司", startTime, endTime, carry+flightNo, null, null, null, type);
				if(!flighObje.getJSONObject("cBrand").isNullObject()) 
					cabinData.add(flighObje.getJSONObject("cBrand"));
				if(!flighObje.getJSONObject("fBrand").isNullObject()) 
					cabinData.add(flighObje.getJSONObject("fBrand"));
				if(!flighObje.getJSONObject("yBrand").isNullObject())
					cabinData.add(flighObje.getJSONObject("yBrand"));
				
				if(cabinData.size()>0){
					Double lowestPrice = 0d, lowestTaxesPrice=0d;
					for(JSONObject c : cabinData){
						CabinEntity cabinEntity=PlaneInfoEntityBuilder.buildCabinInfo(
								c.getString("brandName"), c.getString("cabin"),c.getString("brandName"), getFuelTax(flighObje).toString(),
								c.getString("price"), null, null, null, CabinEntity.class);
						singleEntity.getCabins().add(cabinEntity);
						if(lowestPrice == 0d || cabinEntity.getPrice() < lowestPrice){
							lowestPrice = cabinEntity.getPrice();
							lowestTaxesPrice = cabinEntity.getTaxesPrice();
						}
					}
					singleEntity.setTotalLowestPrice(lowestPrice);
					singleEntity.setTotalLowestTaxesPrice(lowestTaxesPrice);
					singleEntity.setSumLowestPrice(lowestPrice+lowestTaxesPrice);
				}else
					throw new FlightInfoNotFoundException("没有舱位");
				
				result.add(singleEntity);
			}
			return result;
		}finally{
			cabinData = null;
			 flighObje=null;
			 jsonArr = null;
			 singleEntity=null;
		}
	}
	
	/**
	 * 获得税费和
	*/
	public Double getFuelTax(JSONObject json){
		Double tax = 0d;
		JSONArray fuelTaxs = json.getJSONArray("fuelTax");
		for(int i = 0 ;i < fuelTaxs.size(); i++){
			tax += fuelTaxs.getDouble(i);
		}
		return tax;
	}
	
	/**
	 * 解析飞行时间
	 * travelTime : "1小时10分"
	*/
	public Long flightTime(String timeStr){
		Long timeLong=0l;
		if(timeStr !=null && !timeStr.equals("")){
			String h=null,m=null;
			h=timeStr.split("小时")[0];
			m=RegHtmlUtil.regStr(timeStr.split("小时")[1], "(\\d{1,2})");
			if(h !=null && !h.equals(""))
				timeLong+=Long.parseLong(h)*60;
			if(m !=null && !m.equals(""))
				timeLong+=Long.parseLong(m);
		}
		
		return timeLong*60*1000;
	}

		
	@Override
	public String getUrl() throws Exception {
		StringBuilder url = new StringBuilder();
		url.append("http://et.xiamenair.com/xiamenair/book/findFlights.json?");
		url.append("r=").append(random);
		url.append("&takeoffDate=").append(taskQueue.getFlightDate());
		url.append("&returnDate=").append("");
		url.append("&orgCity=").append(taskQueue.getFromCity());
		url.append("&dstCity=").append(taskQueue.getToCity());
		url.append("&tripType=0");
		url.append("&_=").append(System.currentTimeMillis());
		return url.toString();
	}
	
	
	
	
	

	@Override
	public boolean validateFetch(Object fetchObject) throws Exception {
		if (fetchObject == null) {
			throw new Exception("厦门航空网页数据为空");
		}
		String pageText = fetchObject.toString().replaceAll("\\s", "");
		if (pageText.length() < 1000) {
			throw new Exception("获取页面失败，页面数据少于1000");
		}
		if (pageText.matches(".*没找到您要预订的航班.*")) {
			throw new FlightInfoNotFoundException();
		}
		if (pageText.matches(".*Theflightyouwanttobookhasnotbeenfound.*")) {
			throw new FlightInfoNotFoundException();
		}
		if (pageText.matches(".*当天无符合条件的航班.*")) {
			throw new FlightInfoNotFoundException("当天没有符合该条件的航班,可能已经起飞！");
		}
		if (pageText.matches(".*noflightmatchesyourrequest.*")) {
			throw new FlightInfoNotFoundException("当天没有符合该条件的航班,可能已经起飞！");
		}
		if (pageText.matches(".*Noflightsavailableontheselectedday.*")) {
			throw new FlightInfoNotFoundException("当天没有符合该条件的航班,可能已经起飞！");
		}
		if (pageText.matches(".*该天没有航班，请更改日期重新查.*")) {
			throw new FlightInfoNotFoundException();
		}
		if (pageText.matches(".*您所请求的网址（URL无法获取.*")
				|| pageText.matches(".*TherequestedURLcouldnotberetrieved.*")
				|| pageText
						.matches(".*Therequesttimedoutbeforethepagecouldberetrieved.*")) {
			logger.error("厦门航空获取的页面被拒绝了");
			throw new Exception("TherequestedURLcouldnotberetrieved");
		}
		if(pageText.matches(".*Thesystemisbusy,pleasetryagainlater.*")){
			throw new Exception("The system is busy, please try again later");
		}
		
		return true;
	}
}


